import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import { renderWithQiankun, qiankunWindow } from 'vite-plugin-qiankun/es/helper'
import app from './App.vue'
import routes from './router'
import actions from './actions'

let root = null
// renders 生命周期函数
renderWithQiankun({
  bootstrap (props) {
    // console.log('bootstrap', props)
  },
  mount (props) {
    console.log('mount', props)
    render(props)
  },
  unmount () {
    root.unmount()
  },
  update () {}
})

// 独立运行时
if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
  render({})
}

// 渲染挂载页面
function render (props) {
  const { container, onGlobalStateChange, setGlobalState } = props
  const router = createRouter({
    history: createWebHistory(
      qiankunWindow.__POWERED_BY_QIANKUN__ ? props.path : '/'
    ),
    routes
  })
  root = createApp(app)

  root.use(router)
  const dom = container
    ? container.querySelector('#app')
    : document.getElementById('app')
  root.mount(dom)
  /* 父应用传值 */
  if (props) {
    // /* 将props抽离出来给actions实例 */
    // actions.setActions(props)
    /* 将主应用props的onGlobalStateChange，setGlobalState方法挂载到全局 */
    root.config.globalProperties.$onGlobalStateChange = onGlobalStateChange
    root.config.globalProperties.$setGlobalState = setGlobalState
    root.config.globalProperties.$parentRouter = props.router
  }
}
// console.log('qiankunWindow', qiankunWindow)
